// 字符串转dom
export function stringToFragmentDom(htmlStr: string) {
  const range = document.createRange()
  return range.createContextualFragment(htmlStr)
}
// 字符串转dom
export function stringToHtmlDom(htmlStr: string) {
  const domParser = new DOMParser()
  const doc = domParser.parseFromString(htmlStr, 'text/html')
  return doc.body;
}
// 根据标签向上查找父元素
export function getParentElementByTagName(child:ChildNode, tagName: string) {
  tagName = tagName.toUpperCase()
  if(child.parentElement?.tagName == tagName) {
    return child.parentElement
  } else {
    if(child.parentElement?.tagName == 'BODY') { // 如果查到最上级body节点还没找到元素则抛出异常
      throw new Error('未查询到指定父元素')
    }
    if(child.parentElement) {
      return getParentElementByTagName(child.parentElement, tagName)
    }
  }
}
// 根据id向上查找父元素
export function getParentElementById(child:ChildNode, parentId:string) {
  if(child.parentElement?.id == parentId) {
    return child.parentElement
  } else {
    if(child.parentElement?.tagName == 'BODY') { // 如果查到最上级body节点还没找到元素则抛出异常
      throw new Error('未查询到指定父元素')
    }
    if(child.parentElement) {
      return getParentElementById(child.parentElement, parentId)
    }
  }
}
// 获取指定区间随机数
export function getRandomNumber(min: number, max: number) {
  return (parseFloat(Math.random().toFixed(2)) * (max - min + 1)) + min;
}
// 关键字添加样式
export function addKeywordStyle(keyword: string, content: string, className: string ='', style?: string, ) {
  const html = content.replace(new RegExp(`${keyword}`, 'gi'), (match: string) => {
      return `<span style="${style}">${match}</span>`
  })
  const range = document.createRange()
  const fragment = range.createContextualFragment(html)
  const div = document.createElement('div')
  div.className = className
  div.append(fragment)
  return div
}

// 倒计时格式化
export function formatSeconds(seconds: number, format: string= 'hh:mm:ss'): string {
  let [hour, minute, second]: Array<number> = [0, 0, 0];
  if (seconds >= 3600) {
    hour = Math.floor((seconds % (24 * 3600)) / 3600);
  }
  if (seconds >= 60) {
    if(!/h/g.test(format)) { // 不显示小时
      minute = Math.floor(seconds / 60);
    } else { // 显示小时
      minute = Math.floor((seconds % 3600) / 60);
    }
  }
  second = Math.floor(seconds % 60);
  const timeSource: any = {
		'h': hour.toString(), // 小时
		'm': minute.toString(), // 分钟
		's': second.toString(), // 秒
	}
  for (const key in timeSource) {
    const [ret] = new RegExp(`${key}+`).exec(format) || []
    if(ret) {
      format = format.replace(ret, (match) => match.length == 2 ?timeSource[key].padStart(2, '0'):timeSource[key]);
    }
  }
  return format
}